package com.supply.dl.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.supply.dl.SupplyApplication;
import com.supply.dl.activity.ScanActivity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class Utils {
    static final String TAG = "SinceUtils";
    private static final String DEF_SHARED_FILE = TAG;
    private static final Object LOCKER = new Object();
    private static final String PREFS_DEVICE_ID = "device_id";
    private static final String DEVICESYN = "devicesyn";
    private static String APPKEY = "d9901bd818969018";
    private static boolean isErrorTime;
    private static long diffValueTime;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLORDRAWABLE_DIMENSION = 2;

    public static String long2Str(long time) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(new Date(time));
            return date;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return "1970-01-01 08:00:00";
    }
    /**
     * 判断字符串是否为null
     *
     * @return true, 待价侧字符串不为空，fasle,待价侧字符串为空或不合法
     */
    public static boolean isNotEmpty(String str) {
        if (null == str) {
            return false;
        }
        if ("".equals(str)) {
            return false;
        }
        if ("null".equals(str)) {
            return false;
        }
        return true;
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(DEF_SHARED_FILE, 0);
    }

    /**
     * 获取时间戳
     *
     * @return 时间戳
     */
    public static String genTimestamp() {

        if (isErrorTime && diffValueTime != 0)
            return String.valueOf(System.currentTimeMillis() / 1000 + diffValueTime);

        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 标记为上报时间不合法
     *
     * @param isErrortime 上报时间是否不正确
     * @param validTime   有效时间
     */
    public static void markErrorTimestamp(boolean isErrortime, long validTime) {

        isErrorTime = isErrortime;
        diffValueTime = validTime - System.currentTimeMillis() / 1000;
    }

    /**
     * 获取数据传输的秘钥
     *
     * @return 当前应用的版本号
     */
    public static String getAppKey() {
        return APPKEY;
    }

    /**
     * 从网络上获取图片
     *
     * @param path 图片路径
     * @return 图片的流InputStream
     */
    public static InputStream getImageStream(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return conn.getInputStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getLanguage(Context mContext) {
        Locale locale = mContext.getResources().getConfiguration().locale;
        if (locale == null) locale = Locale.getDefault();
        String language = locale.getLanguage();
        String country = locale.getCountry();
        if (!TextUtils.isEmpty(country)) language += "_" + country;
        return language;
    }

    /**
     * 写入配置到 SharedPreferences 中，如果 msg==null，则移除
     */
    public synchronized static boolean writeConfig2SharedPreferences(Context ctx, String key, String msg) {
        try {
            final SharedPreferences prefs = getSharedPreferences(ctx);
            if (msg == null) {
                if (prefs.contains(key)) return prefs.edit().remove(key).commit();
            } else {
                return prefs.edit().putString(key, encrypt(msg, key)).commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String MD5Encode(byte[]... toencode) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(K_MD5);
            md5.reset();
            for (byte[] bs : toencode) {
                md5.update(bs);
            }
            return HexEncode(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 加密
     */
    public static String encrypt(String msg, String key) {
        byte[] bytes = enCrytpDes(msg, K_MD5 + key + K_SP + K_DES);
        String md5 = MD5Encode(bytes, key.getBytes(), K_SP.getBytes());
        String base64 = Base64.encodeToString(bytes, Base64.NO_WRAP | Base64.NO_PADDING);
        return base64 + K_SP.charAt(1) + md5 + "==";
    }

    static String K_DES = "DES";
    static String K_MD5 = "MD5";
    static String K_SP = "A/=B";

    public static byte[] enCrytpDes(String txt, String key) {
        try {
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
            SecretKeyFactory skeyFactory = SecretKeyFactory.getInstance(K_DES);
            Cipher cipher = Cipher.getInstance(K_DES);
            SecretKey deskey = skeyFactory.generateSecret(desKeySpec);
            cipher.init(Cipher.ENCRYPT_MODE, deskey);
            return cipher.doFinal(txt.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String HexEncode(byte[] toencode) {
        return HexEncode(toencode, HEX_CHARS_UPPER);
    }

    public static String HexEncode(byte[] toencode, char[] chars) {
        int size = toencode.length;
        char[] out = new char[size + size];
        for (int i = 0, j = 0; i < size; i++, j += 2) {
            out[j] = chars[(toencode[i] >> 4) & 0x0f];
            out[j + 1] = chars[toencode[i] & 0x0f];
        }
        return new String(out);
    }

    private static final char[] HEX_CHARS_UPPER = "0123456789ABCDEFGH".toCharArray();

    /**
     * 从 SharedPreferences 中读取配置
     */
    public synchronized static String readConfigFromSharedPreferences(Context ctx, String key) {
        try {
            SharedPreferences sp = getSharedPreferences(ctx);
            String s = sp.getString(key, null);
            if (s == null) return null;
            return decrypt(s, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密，若无效则反回null
     */
    public static String decrypt(String msg, String key) {
        int pos = msg.lastIndexOf(K_SP.charAt(1));
        if (pos > 0 && pos < msg.length() - 2) {
            String md5 = msg.substring(pos + 1, msg.length() - 2);
            String base64 = msg.substring(0, pos);
            byte[] bytes = Base64.decode(base64, Base64.NO_WRAP | Base64.NO_PADDING);
            if (md5.equals(MD5Encode(bytes, key.getBytes(), K_SP.getBytes()))) {
                return deCryptDes(bytes, 0, bytes.length, K_MD5 + key + K_SP + K_DES);
            }
        }
        return null;
    }

    public static String deCryptDes(byte[] bytes, int off, int len, String key) {
        try {
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
            SecretKeyFactory skeyFactory = SecretKeyFactory.getInstance(K_DES);
            Cipher cipher = Cipher.getInstance(K_DES);
            SecretKey deskey = skeyFactory.generateSecret(desKeySpec);
            cipher.init(Cipher.DECRYPT_MODE, deskey);
            return new String(cipher.doFinal(bytes, off, len), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean matchPhone(String regExp, String value) {
        if (StringUtils.isBlank(regExp)) return false;
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(value);
        return m.matches();
    }

    public static String convertTime(long currentTime, long pushTime) {
        // 计算当前时间和发布时间之间的间隔
        long time = currentTime - pushTime;
        // 秒
        long second = time / 1000;
        if (second < 60) {
            return "刚刚";
        }

        // 分
        long minute = second / 60;
        if (minute < 60) {
            minute = minute <= 0 ? 1 : minute;
            return minute + "分钟前";
        } else {
            // 小时
            long hour = minute / 60;
            if (hour < 24) {
                if (hour == 0) {
                    hour = 1;
                }
                return hour + "小时前";
            }
            // 天
            long day = hour / 24;
            if (day < 30) {
                if (day == 0) {
                    day = 1;
                }
                return day + "天前";
            }

            long month = day / 30;
            if (month < 12) {
                if (month == 0) {
                    month = 1;
                }
                return month + "月前";
            }

            //年
            long year = day / 365;

            if (year >= 1) {
                return year + "年前";
            }

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(currentTime);
            String currentTimeDate = dateFormat.format(calendar.getTime());
            calendar.setTimeInMillis(pushTime);
            String pushTimeDate = dateFormat.format(calendar.getTime());
            int currentYear = Integer.parseInt(currentTimeDate.substring(0, 4));
            int pushTimeYear = Integer.parseInt(pushTimeDate.substring(0, 4));
            //当前年之前发布
            if (currentYear > pushTimeYear) {
                return (currentYear - pushTimeYear) + "年前";
            }

            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy年MM月");
            return sDateFormat.format(new Date(pushTime));

        }
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    public static void call(Context context, String phone) {
        if (StringUtils.isBlank(phone)) return;
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;
            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取屏幕的宽度
     *
     * @param context 上下文
     * @return 屏幕的宽度
     */
    public static int getWindowWidth(Context context) {
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * dp转px
     */
    public static int dp2px(float dpValue)
    {
        Context context = SupplyApplication.getAppContext();
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取屏幕的高度
     *
     * @param context 上下文
     * @return 屏幕的宽度
     */
    public static int getWindowHeigh(Context context) {
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * 将String 变成toRequestBody
     *
     * @param value
     * @return
     */
    public static RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }

    /**
     * 将String 变成toRequestBody
     *
     * @param value
     * @return
     */
    public static RequestBody toRequestBodyJSON(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), value);
        return requestBody;
    }

    /**
     * 打开扫码界面
     *
     * @param mActivity
     */
    public static void startScanActivity(Activity mActivity) {
        new com.google.zxing.integration.android.IntentIntegrator(mActivity) //
                .setOrientationLocked(false)//
                .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是ScanActivity
                .initiateScan(); // 初始化扫描
    }
}
